package com.bluefoxyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bluefoxyu.domain.dto.StudentDTO;
import com.bluefoxyu.domain.entity.Course;
import com.bluefoxyu.domain.entity.Enrollment;
import com.bluefoxyu.domain.entity.Student;
import com.bluefoxyu.domain.entity.Teacher;
import com.bluefoxyu.domain.vo.StudentCourseVO;
import com.bluefoxyu.domain.vo.StudentVO;
import com.bluefoxyu.exception.WorkException;
import com.bluefoxyu.mapper.CourseMapper;
import com.bluefoxyu.mapper.EnrollmentMapper;
import com.bluefoxyu.mapper.StudentMapper;
import com.bluefoxyu.mapper.TeacherMapper;
import com.bluefoxyu.properties.JwtClaimsConstant;
import com.bluefoxyu.properties.JwtProperties;
import com.bluefoxyu.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bluefoxyu.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生信息表 服务实现类
 * </p>
 *
 * @author bluefoxyu
 * @since 2024-06-16
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private EnrollmentMapper enrollmentMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private TeacherMapper teacherMapper;

    @Override
    public StudentVO login(StudentDTO studentDTO) {

        String username= studentDTO.getStudentId();
        String password= studentDTO.getPassword();

        // 根据用户名查询数据库
        QueryWrapper<Student> wrapper=new QueryWrapper<>();
        wrapper.lambda()
                .eq(Student::getStudentId,username);
        Student student = studentMapper.selectOne(wrapper);

        // 判断查询结果是否为null,根据名字查询如果账户里面没有那个人则退出查询
        // 如果为null，则抛出AccountNotFoundException异常，并返回错误信息
        if (student == null) {
            throw new WorkException("账号不存在");
        }
        // 判断密码是否正确，如果密码不正确，则抛出异常，并返回错误信息
        //密码比对
        boolean flag= password.equals(student.getPassword());
        if (!flag) {
            throw new WorkException("密码错误");
        }

        //登录成功后返回jwt令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,student.getId());

        //生成token，注入相关jwtProperties配置属性
        String token= JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        StudentVO studentVO=new StudentVO();
        BeanUtils.copyProperties(student,studentVO);
        studentVO.setToken(token);

        return studentVO;
    }

    @Override
    public BigDecimal selectStudentCredit(Integer studentId) {

        QueryWrapper<Enrollment>wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(Enrollment::getStudentId,studentId);
        BigDecimal totalCredit=BigDecimal.ZERO;
        //在成绩表查询学生修的课程信息
        List<Enrollment> enrollmentList = enrollmentMapper.selectList(wrapper);
        for (Enrollment enrollment : enrollmentList) {
            Integer courseId = enrollment.getCourseId();
            Course course = courseMapper.selectById(courseId);
            BigDecimal credits = course.getCredits();
            totalCredit=totalCredit.add(credits);
        }

        return totalCredit;
    }

    @Override
    public List<StudentCourseVO> selectStudentCourse(Integer currentId) {

        //根据学生id查询学生信息
        Student student = studentMapper.selectById(currentId);

        // 封装返回信息
        List<StudentCourseVO> studentCourseVOList = new ArrayList<>();

        //根据学生id查询学生选课信息
        QueryWrapper<Enrollment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Enrollment::getStudentId, currentId);
        List<Enrollment> enrollmentList = enrollmentMapper.selectList(wrapper);
        for (Enrollment enrollment : enrollmentList) {

            //查课程
            Integer courseId = enrollment.getCourseId();
            Course course = courseMapper.selectById(courseId);
            BigDecimal credits = course.getCredits();
            Teacher teacher = teacherMapper.selectById(course.getTeacherId());

            StudentCourseVO build = StudentCourseVO.builder()
                    .id(student.getId())
                    .name(student.getName())
                    .studentId(student.getStudentId())
                    .courseName(course.getName())
                    .credits(credits)
                    .grade(enrollment.getGrade())
                    .teacherId(teacher.getId())
                    .teacherName(teacher.getName())
                    .jobTitle(teacher.getJobTitle())
                    .build();

            studentCourseVOList.add(build);
        }
        return studentCourseVOList;
    }

}
